import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import AntTabs, {
  HocVerticalLeftStyleTab,
} from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { TreeSelectKeyContext } from '../../index';
import { getSubjectList, getSubjectType } from '../../service';


import ProjectTreeTabsComponent from '@/pages/components/ProjectTreeTabsComponent';

import { flattenTreeDataWithLeafCheck } from './util';

const ProjectTreeComponent = React.forwardRef((props: any, ref: any) => {
  const { AccountDataID } = props;
  const { setLeftParamsObj } = useContext<any>(TreeSelectKeyContext);

  const { initialState } = useModel('@@initialState');
  const { username } = initialState?.curUser;
  const { dbname } = initialState?.curPart;
  const projectTreeTabsComponentRef = useRef<any>();
  const [entryTabsData, setEntryTabsData] = useState<any[]>([]);
  const [tbsStates, setTbsStates] = useState<any>('0');
  const tbsStatesRef = useRef<string>('0');

  const [entryFilterTreeData, setEntryFilterTreeData] = useState<any[]>([]); // 树的过滤数据
  const entryTreeDataRef = useRef<any>();
  // const [visiblePopupKey, setVisiblePopupKey] = useState<string>('');

  const getSubjectTypeData = async (DataId: any) => {
    const res = await getSubjectType({
      dbname,
      Data_ID: DataId,
    });
    if (res.success) {
      res.data.unshift({ code: '0', type: '全部' });
      setEntryTabsData(res.data);
      setTbsStates('0');
      tbsStatesRef.current = '0';
    }
  };
  const changeCurNode = (nodeObj: any) => {
    console.log(`🚀--Nice ~ changeCurNode ~ nodeObj:`, nodeObj);

    (projectTreeTabsComponentRef.current.treeRefFun() as any)?.treeRef.current.instance?.selectItem(nodeObj.ID);
    setLeftParamsObj((oldData: any) => {
      let newData: any = {
        ...oldData,
        selectTreeNode: nodeObj,
      };
      return newData;
    });
  };

  // 右侧 切换方法
  const getSubjectListData = useCallback(
    async (r: string, isChangeKey: boolean = false) => {
      const resF = entryTabsData.filter((item: any) => r === item.code);
      const filStr = resF[0]?.type ?? '全部';
      setTbsStates(r);
      tbsStatesRef.current = r;
      if (entryTreeDataRef.current?.length) {
        if (filStr === '全部') {
          setEntryFilterTreeData(entryTreeDataRef.current);
        } else {
          const KMLXData = entryTreeDataRef.current.filter((item: any) => {
            return item.KMLX && item.KMLX.includes(filStr);
          });
          setEntryFilterTreeData(KMLXData);
        }
      }
    },
    [entryTreeDataRef.current, entryTabsData],
  );
  // 获取树表格数据 设置属性的时候
  const getSubjectListDatas = async (DataId: any) => {
    entryTreeDataRef.current = [];
    const res = await getSubjectList({
      dbname,
      Data_ID: DataId,
      isHasFZZ: true,
    });
    if (res.success) {
      // setEntryFilterTreeData(res.data);
      if (res.data?.length) {
        // getSubjectListData(tbsStatesRef.current);
        const flatData = flattenTreeDataWithLeafCheck(res.data); // 转换为平铺结构并检查叶子节点
        console.log(`🚀--Nice ~ getSubjectListDatas ~ flatData:`, flatData)
        entryTreeDataRef.current = flatData;
        setEntryFilterTreeData(flatData);
        setTimeout(() => {
          changeCurNode(flatData[0]);
        }, 300);
      }
    }
  };

  const treeTabsReloa = (yearData: any) => {
    setTbsStates('0');
    tbsStatesRef.current = '0';
    getSubjectTypeData(yearData);
    getSubjectListDatas(yearData);
  }


  useEffect(() => {
    if (AccountDataID) {
      treeTabsReloa(AccountDataID)
    }
  }, [AccountDataID]);




  return (
    <div
      style={{
        height: '100%',
        padding: '0px',
        display: 'flex',
        justifyContent: 'left',
        alignItems: 'flex-start',
      }}
    >
      <HocVerticalLeftStyleTab
        activeKey={tbsStates}
        className="AccountSubjectsTabs"
        style={{ marginTop: '-8px' }}
        tabPosition="left"
        tabBarStyle={{ background: '#FFF' }}
        onChange={(e: any) => {
          getSubjectListData(e || '0', true);
        }}
      >
        {Array.isArray(entryTabsData) ? (
          entryTabsData.map((item: any) => {
            return <AntTabs.Panel tab={item.type} key={item.code} style={{ marginTop: '5px' }} />;
          })
        ) : (
          <></>
        )}
      </HocVerticalLeftStyleTab>

      <ProjectTreeTabsComponent
        ref={projectTreeTabsComponentRef}
        AccountDataID={AccountDataID}
        treeSelectNodeFunc={(nodeObj: any) => {
          setLeftParamsObj((oldData: any) => {
            let newData: any = {
              ...oldData,
              selectTreeNode: nodeObj,
            };
            return newData;
          });
        }}
        treeTabsReloadFunc={() => {
          treeTabsReloa(AccountDataID);
        }}
        AccountTreeList={entryFilterTreeData}
      />
    </div>
  );
});

export default ProjectTreeComponent;
